package com.example.shop.user.config;

import com.example.shop.user.interceptor.LoginInterceptor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.converter.StringHttpMessageConverter;
import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.InterceptorRegistration;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

import java.nio.charset.Charset;
import java.util.List;


@Configuration("userSpringMvcExtendsConfig")
public class SpringMvcExtendsConfig implements WebMvcConfigurer {

    @Autowired
    LoginInterceptor loginInterceptor;
    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        //将拦截器添加到spring拦截器列表中，
        InterceptorRegistration interceptorRegistration = registry.addInterceptor(loginInterceptor);
        //配置该拦截器的路径
        interceptorRegistration.addPathPatterns(
                "/user/bind/**",
                "/user/unbind/**",
                "/user/update/**",
                "/user/get/**",
                "/user/cancellation/**",
                "/user/enable/**",
                "/user/ban/**",
                "/user/goods/**",
                "/user/order/browse/**",
                "/user/goods/evaluation/**",
                "/user/browsingHistory/**",
                "/user/collection/**",
                "/user/linkman/**",
                "/user/websocket/**",
                "/user/chatMessage/**"
        );
        //设置该拦截器的排除拦截路径
        interceptorRegistration.excludePathPatterns("/user/goods/browse/**","/user/goods/buy/success/**");
        //设置该拦截器的拦截顺序order
        interceptorRegistration.order(1);
    }


    /**
     * 跨域设置
     * @param registry 全局跨域配置注册器
     */
    @Override
    public void addCorsMappings(CorsRegistry registry) {
        //允许跨域请求的url路径
        registry.addMapping("/**")
                //允许跨域的域名，无论从谁都可以请求本网站
                .allowedOrigins("*")
                //允许跨域包含任何头信息
                .allowedHeaders("*")
                //允許跨域的方法
                .allowedMethods("*")
                //允许跨域请求的方法
                .allowedMethods("PUT", "DELETE","POST", "GET")
                //端点发送凭据(如跨域请求的cookie),如果非常信任，则可以设置为true
                .allowCredentials(true)
                //浏览器允许客户端访问的响应头列表。
//                .exposedHeaders()
                //预检请求的有效期，单位为秒。有效期内，不会重复发送预检请求。
                //当预检请求通过后，浏览器才会发送真实请求到服务器。这样就实现了跨域资源的请求访问。
                .maxAge(1800);
    }
}
